﻿using System.IO;

using Utilities.Media.Audio;
using Utilities.Media.Audio.Pcm;
using Utilities.Media.Containers.Wav;

namespace Utilities.Media.Containers
{
    public class WavContainer : RiffContainer
    {
        public FmtChunk Format { get; protected set; }
        public DataChunk Data { get; protected set; }

        public AudioStream AudioStream { get; protected set; }

        private long dataPosition;

        // Lecture
        public WavContainer(string path) : this(File.Open(path, FileMode.Open))
        {
        }
        public WavContainer(Stream stream) : base(stream)
        {
            ReadHeader();
        }

        // Ecriture
        public WavContainer(string path, short numChannels, int sampleRate, short bitsPerSample, AudioFormat audioFormat) : this(File.Open(path, FileMode.Create), numChannels, sampleRate, bitsPerSample, audioFormat)
        {
        }
        public WavContainer(Stream stream, short numChannels, int sampleRate, short bitsPerSample, AudioFormat audioFormat) : base(stream, "WAVE")
        {
            Format = new FmtChunk(numChannels, bitsPerSample, sampleRate, audioFormat);
            Data = new DataChunk();

            WriteHeader();
        }

        public override void ReadHeader()
        {
            base.ReadHeader();

            // Lecture des headers WAV (format RIFF)
            Format = new FmtChunk(BaseStream);
            Data = new DataChunk(BaseStream);

            // Détection du flux audio
            dataPosition = BaseStream.Position;
            switch (Format.AudioFormat)
            {
                case AudioFormat.PCM:
                    Streams.Add(new PcmStream(BaseStream, Format.NumChannels, Format.BitsPerSample, Format.SampleRate));
                    break;
            }
            AudioStream = Streams[0] as AudioStream;
        }
        public override void WriteHeader()
        {
            // Ecriture du header RIFF
            base.WriteHeader();

            // Ecriture des headers WAV fmt et data
            BaseStream.Write(Format.ID);
            BaseStream.Write(Format.Size);
            BaseStream.Write(Format.AudioFormat);
            BaseStream.Write(Format.NumChannels);
            BaseStream.Write(Format.SampleRate);
            BaseStream.Write(Format.ByteRate);
            BaseStream.Write(Format.BlockAlign);
            BaseStream.Write(Format.BitsPerSample);

            BaseStream.Write(Data.ID);
            BaseStream.Write(Data.Size);
        }
    }
}
